var kyyData = {
  pddData: {
    goods: [],
    // 价格类型 1 运费公式 2 价格*5
    priceType: "1",
    // 第一个SKU
    firstSku: "30*40",
    // 初始价
    originalPrice: "1872",
    // 商品标题
    goodsTitle: "~~~~",
    // 商品描述
    goodsDesc: "~~~~",
    // 第一个分类描述
    firstClassify: "",
    // 初始化的分类描述 根据是否为空可判断是否只有一个SKU
    filterSkuKind: "",
    pddKeyWordDes: "",
    goodsDetails: [],
  }
};

var kyy = {
  tbRate: 3.5,
  dateStr: "20000101",
};

function getTbRate() {
  return parseFloat($("#tbRate").val());
}

async function oneKeyDiscount(discount = false) {
  await wait(500);

  // 跳转
  anchors("商品规格列表");
  await wait(800);

  // 设置最低价格
  // await setTargetPrice();
  // await wait(1200);


  // 点击折扣活动
  $('input[aria-label="折扣活动"]').click();
  await wait(500);

  // 选择折扣
  $('.v-input--selection-controls__input input[role="radio"]').eq(0).click();
  await wait(200);

  // 点击确定按钮
  $(".v-dialog--scrollable .v-btn__content").eq(3).click();

  if (discount) {
    await inputValue($('input[aria-label="折扣"]')[1], discount);
  }
  // 设置折扣值
  // 判断价格模板类型
  else {
    await inputValue(
      $('input[aria-label="折扣"]')[1],
      discount ? discount : 50
    );
  }
  await wait(500);

  // 打开折扣按钮
  let disLen = $('div[title="商品规格列表"]').next().find("th").length;
  let discountRadio;
  for (let i = 0; i < disLen; i++) {
    var text = $('div[title="商品规格列表"]').next().find("th").eq(i).text();
    if (text == '折扣') {
      discountRadio = $('div[title="商品规格列表"]').next().find("th").eq(i).find("input")
      break;
    }
  }
  discountRadio.click();
  await wait(500);

  // 全选了才能操作
  // 重新全部check
  let allCheck = $('div[title="商品规格列表"]').next().find("th").eq(0).find("input")[0];
  allCheck.click();
  await wait(500);
  allCheck.click();
  await wait(500);

  // 折扣设置一键设置
  $('div[title="折扣设置"]').parent().find(".v-btn__content").eq(0).click();
  await wait(500);

  // 取整按钮
  var floorBtn = getHandleBySelectorAndText(
    $(".v-menu__content .v-list__tile__title"),
    "取整"
  );
  floorBtn.click();
  await wait(500);
}

async function expressInfo() {
  anchors("物流信息");

  // 物流方式
  for (let item of wlfs) {
    let handle = $(`#logisticsInformation input[aria-label="${item}"]`);
    if (handle.length > 0) {
      await checkBox(handle[0], handle[0].getAttribute("aria-checked"), false);
    }
  }
}

async function initRate() {
  console.log("initRateBtn");

  var firstBtn = $('#main .v-tabs__item:contains("全球商品")')[0];
  firstBtn.click();

  await wait(2000);

  anchors("价格库存");
  await wait(2000);
  anchors("物流信息");
  await wait(2000);

  // 表头
  var ths = Array.from($("#shopee-variation-table thead th"));
  // 价格索引
  var idx = -1;
  ths.forEach((e, index) => {
    if (e.textContent.includes("价格")) {
      console.log("第一的表头:", e.textContent);
      idx = index;
    }
  });
  // 获取表身第一个价格
  var price1 =
    $("#shopee-variation-table tbody td")
      .eq(idx)
      .find(".k-text-field-content-value__text").length == 0
      ? $("#shopee-variation-table tbody td").eq(idx).find("span")[0].textContent
      : $("#shopee-variation-table tbody td")
        .eq(idx)
        .find(".k-text-field-content-value__text")[0].textContent;
  console.log(price1);

  // ------------------------------- //
  let state = $("#siteSelect").val();
  console.log("选择的跨境：", state);
  var secondBtn = $(`#main .v-tabs__item:contains("${state}")`)[0];
  secondBtn.click();

  await wait(2000);

  await anchors("价格库存");
  await wait(2000);
  await anchors("物流信息");
  await wait(2000);

  // 其他站点多了个选择框
  // 表头
  var ths1 = Array.from($("#variation-table thead th"));
  // 价格索引
  var idx1 = -1;
  ths1.forEach((e, index) => {
    if (e.textContent.includes("价格")) {
      console.log("第二的表头:", e.textContent);
      idx1 = index;
    }
  });

  var price2 =
    $("#variation-table tbody td")
      .eq(idx1)
      .find(".k-text-field-content-value__text").length == 0
      ? $("#variation-table tbody td").eq(idx1).find("span")[0].textContent
      : $("#variation-table tbody td")
        .eq(idx1)
        .find(".k-text-field-content-value__text")[0].textContent;

  console.log("price1:", price1);
  console.log("price2:", price2);

  let twRate = price2 / price1;
  console.log(typeof twRate, ":", twRate);

  if (typeof twRate == "number") {
    $("#tbRate").val(twRate);
    $("#tbRate").trigger("change");
  }

}

// 添加商品描述
function addGoodsDesc() {
  return new Promise(async (resolve, reject) => {
    // 找到句柄
    let handle = $('#appRoot  div[title="描述"]').next();
    let inputHandle = handle.find("textarea")[0];
    handle = handle.find(".shopee-sensitive-words-input__mask");

    handle.click(async (e) => {
      await wait(500);

      kyyData.pddData.goodsDesc = editGoodsDesc();

      // 点击后出来input才能执行，需要放在timeout中
      await inputValue(inputHandle, kyyData.pddData.goodsDesc);
      // 清除事件
      handle.unbind(e);
      resolve();
    });

    // 手动触发
    handle[0].click();
  });
}

// 编辑商品详情
function editGoodsDesc() {
  let temp = "";
  let longestSkuLength = 0;
  let pddData = kyyData.pddData;
  if (needEmoji) {
    // 设置商品描述前缀
    temp = dlData.prefix + "\n\n🔹🔹🔹🔹🔹🔹🔹🔹🔹🔹\n😀【商品详情】😀\n";

    // 获取最长的SKU
    if (strlen(pddData.goods[pddData.goods.length - 1].sku) > longestSkuLength) {
      longestSkuLength = strlen(pddData.goods[pddData.goods.length - 1].sku);
    }

    // 添加商品详情属性
    pddData.goodsDetails.forEach((e) => {
      temp += e + "\n";
    });
    temp += "🔹🔹🔹🔹🔹🔹🔹🔹🔹🔹";
  } else {
    // 设置商品描述前缀
    temp = dlData.prefix + "\n\n====================\n《【商品详情】》\n";

    // 获取最长的SKU
    if (strlen(pddData.goods[pddData.goods.length - 1].sku) > longestSkuLength) {
      longestSkuLength = strlen(pddData.goods[pddData.goods.length - 1].sku);
    }

    // 添加商品详情属性
    pddData.goodsDetails.forEach((e) => {
      temp += e + "\n";
    });
    temp += "====================";
  }

  temp +=
    "\n\n【其他現貨尺寸下標指南】:如價格為290，下標先選擇對應花色，再選擇客製尺寸，數量欄輸入29即可！下单请备注尺寸\n\n【商品尺寸、价格】\n";

  // 添加SKU
  debugger
  console.table([
    { name: "第一个价格", value: pddData.goods[0].originPrice },
    { name: "倍率", value: pddData.originalPrice },
    { name: "汇率", value: getTbRate() },
    { name: "折扣", value: "50%" }
  ]);

  pddData.goods.forEach((element, index1) => {
    element.targetPrice = Math.floor(
      (element.originPrice * pddData.originalPrice * getTbRate()) / 2
    );

    let addSpaceNum = longestSkuLength - strlen(element.sku);
    let str = "";
    for (var i = 0; i < addSpaceNum; i++) {
      str = str + "\xa0";
    }
    temp += `${element.sku}\xa0\xa0\xa0\xa0${str}\xa0\xa0\xa0\xa0${element.targetPrice}元\n`;
  });

  // 添加后缀
  temp += dlData.suffix + "\n\n";

  // 添加关键词
  temp += pddData.pddKeyWordDes + "\n\n";

  return temp;
}


// 翻译
async function translateLanguage() {

  let state = "";

  switch ($("#siteSelect").val()) {
    case "台湾": {
      state = "中文(简体) -> 中文(繁体)";
    }
    default: break;
  }

  if (!state) return;

  $(".bottom-panel button").eq(0).click();
  getHandleBySelectorAndText($(".v-list__tile__title"), state).trigger(
    "click"
  );
  await wait(500);
}